package com.lanou.service.impl;

import com.alibaba.fastjson.JSON;
import com.lanou.entity.Commodity;
import com.lanou.entity.Item;
import com.lanou.entity.TbItem;
import com.lanou.service.CartPageService;
import com.lanou.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CartPageServiceImpl implements CartPageService {

    @Value("${CART_JSON_NOTLOAD_URL}")
    private String CART_JSON_NOTLOAD_URL;

    @Value("${ADD_CART_JSON_NOTLOAD_URL}")
    private String ADD_CART_JSON_NOTLOAD_URL;

    @Value("${ITEM_JSON_URL}")
    private String ITEM_JSON_URL;

    @Override
    public List<Item> showCartNotLand(HttpServletRequest request) {
        return null;
    }

    @Override
    public void addCartNotLand(Long itemId, Integer num) {

    }

    @Override
    public void addCart(Long itemId, Integer num, Long userId) {
        Map<String, Object> params = new HashMap<>();
        params.put("itemId", itemId);
        params.put("num", num);
        params.put("userId", userId);
        String result = HttpClientUtils.post(ADD_CART_JSON_NOTLOAD_URL, params);


    }

    @Override
    public List<Commodity> listCartItems(Long userId) {
        List<Commodity> commodities = HttpClientUtils.getList(CART_JSON_NOTLOAD_URL + "?userId=" + userId,
                Commodity.class);
        // TODO 转换结构
        return commodities;
    }

    @Override
    public String updateCart(String cart, Long itemId, Integer num) {
        TbItem item = findItemById(itemId);
        List<Commodity> commodities = JSON.parseArray(cart, Commodity.class);
        for (Commodity commodity : commodities) {
            if (commodity.getId().equals(itemId)) {
                if (item.getNum() < num) {
                    num = item.getNum();
                }
                commodity.setAmount(num);
                return JSON.toJSONString(commodities);
            }
        }
        Commodity commodity = new Commodity();
        commodity.setId(item.getId());
        commodity.setTitle(item.getTitle());
        commodity.setPrice(item.getPrice());
        commodity.setImg(item.getImage());
        if (item.getNum() < num) {
            num = item.getNum();
        }
        commodity.setAmount(num);
        commodity.setStatus(1);

        commodities.add(commodity);
        return JSON.toJSONString(commodities);
    }

    private TbItem findItemById(Long itemId) {
        //通过id查询接口 获取 数据 //把获取的数据转换为tbItem
        return HttpClientUtils.getObject(ITEM_JSON_URL + itemId, TbItem.class);

    }

}
